package com.farm.view.model.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.List;

public class WdapTxtFileUtils {
	/**
	 * 生成文本文件
	 * 
	 * @param log2
	 *            文件
	 * @param e异常
	 * @throws IOException
	 */
	public static void WriteTxt(File txtFile, List<String> content) throws IOException {
		if (!txtFile.exists()) {
			txtFile.getParentFile().mkdirs();
			txtFile.createNewFile();
		}
		PrintStream ps = new PrintStream(new FileOutputStream(txtFile));
		try {
			ps.println("\n");// 往文件里写入字符串
			for (String line : content) {
				ps.append(line + "\n");// 在已有的基础上添加字符串
			}
		} finally {
			ps.close();
		}
	}

	public static String readTxtFile(File file) {
		StringBuffer buffer = new StringBuffer();
		InputStreamReader read = null;
		InputStream inputStream = null;
		BufferedReader bufferedReader = null;
		try {
			String encoding = HtmlFileHandles.getFileEncode(file);
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				inputStream = new FileInputStream(file);
				read = new InputStreamReader(inputStream, encoding);// 考虑到编码格式
				bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					buffer.append(lineTxt);
				}
			} else {
				System.out.println("找不到指定的文件");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bufferedReader.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				read.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				inputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return buffer.toString();
	}
	
	public static void main(String[] args) {
		System.out.println(readTxtFile(new File("D:\\test\\3.txt")));
	}
}
